import type { ProfileModel, UserPlayListModel, UserRecord } from "../../request/user"
import { reqCouldUserProfile, reqUserPlaylist, reqUserRecord, reqLogout } from "../../request/user"
import { getAstroAndOffsetAge, getProvinceAndCity, localNum } from "../../utils/util"
import { hasLogin } from "../../utils/permission"
import PubSub from "pubsub-js"

Page<DataModel, CustomOptionModel>({
  /**
   * 页面的初始数据
   */
  data: {
    couldUserProfile: {},
    weekData: [],
    favorite: {},
    myList: [],
    subscribedCount: 0,
    collectList: [],
    level: 0,
    moveDistance: 0,
    moveTransition: "all 100ms",
    uid: 0,
    loading: false,
  },

  //#region
  start: 0,
  pageScrollTop: 0, //如果大于0则表示页面不在顶部，不会触发顶部下拉效果

  handleTouchStart(e) {
    this.start = e.touches[0].pageY
    if (this.pageScrollTop) return
    this.setData({ moveTransition: "all 100ms" })
  },

  handleTouchMove(e) {
    if (this.pageScrollTop) return
    const offset = e.changedTouches[0].pageY - this.start
    if (offset <= 0 || offset >= 80) return
    this.setData({ moveDistance: offset })
  },

  handleTouchEnd() {
    if (this.pageScrollTop) return
    this.setData({
      moveDistance: 0,
      moveTransition: "all 400ms;",
    })
  },

  onPageScroll(e) {
    this.pageScrollTop = e.scrollTop
  },
  //#endregion

  onShow() {
    this.getTabBar().setData({
      currentPage: "personal",
    })

    if (!hasLogin()) return
    this.setData({ loading: true })
    const uid = Number(wx.getStorageSync("uid"))

    this.setData({ uid })
    getUserProfile.bind(this)()
    getUserPlayList.bind(this)()
    getUserRecord.bind(this)()
  },

  goPlayList(e) {
    wx.navigateTo({
      url: "/pages/playlist/playlist?id=" + e.currentTarget.dataset.id,
    })
  },

  getSong(e) {
    const { id } = e.detail
    PubSub.publish("playSong", { songId: id })
    PubSub.publish("setPlaylist", { type: "week", data: this.data.weekData, id })
  },

  handleLogout() {
    //清空Storage，并初始化data
    wx.clearStorage()
    reqLogout()
    this.setData({
      couldUserProfile: {},
      weekData: [],
      favorite: {},
      myList: [],
      subscribedCount: 0,
      collectList: [],
      level: 0,
      moveDistance: 0,
      moveTransition: "",
      uid: 0,
    })
    wx.switchTab({
      url: "/pages/index/index",
    })
  },
})

async function getUserProfile(this: Instance) {
  const res = await reqCouldUserProfile(Number(this.data.uid))
  //处理需要计算格式化的几个字段
  const createYear = new Date(Date.now()).getFullYear() - new Date(res.profile.createTime).getFullYear()
  const { astro, offsetAge } = getAstroAndOffsetAge(res.profile.birthday)
  const { provinceName, cityName } = getProvinceAndCity(res.profile.province, res.profile.city)
  res.profile = {
    ...res.profile,
    offsetAge,
    astro,
    provinceName,
    cityName,
    createYear,
  }
  this.setData({
    couldUserProfile: res.profile,
    level: res.level,
  })
}

async function getUserPlayList(this: Instance) {
  const res = await reqUserPlaylist(this.data.uid)
  //所有歌单数据是混在一起的，把”我喜欢的音乐“ “创建的歌单” ”收藏的歌单“ 分别单独分离出来
  const myNickname = this.data.couldUserProfile?.nickname //自己的昵称
  const myList = res.playlist.filter(item => item.creator.userId === this.data.uid)
  const collectList = res.playlist.filter(item => item.creator.userId !== this.data.uid)

  let favoriteIndex!: number
  myList.forEach((item, index) => item.name.includes(myNickname + "喜欢的音乐") && (favoriteIndex = index))
  const favorite = myList.splice(favoriteIndex, 1)[0]

  let subscribedCount = 0
  myList.forEach(item => (subscribedCount += item.subscribedCount))

  this.setData({ favorite, myList, collectList, subscribedCount })
}

async function getUserRecord(this: Instance) {
  const { weekData } = await reqUserRecord(this.data.uid)
  weekData.forEach(item => {
    item.localPlayCount = localNum(item.playCount)
    item.name = item.song.name
    item.picUrl = item.song.al.picUrl
    item.id = item.song.id
  })
  this.setData({ weekData, loading: false })
}

interface DataModel {
  couldUserProfile: Partial<ProfileModel>
  weekData: UserRecord[]
  level: number
  favorite: Partial<UserPlayListModel>
  myList: UserPlayListModel[]
  subscribedCount: number //创建的歌单被收藏的总数，需要计算得出
  collectList: UserPlayListModel[]
  moveDistance: number
  moveTransition: string
  uid: number
  loading: boolean
}

interface CustomOptionModel {
  handleTouchStart: (e: WechatMiniprogram.TouchEvent) => void
  handleTouchMove: (e: WechatMiniprogram.TouchEvent) => void
  handleTouchEnd: (e: WechatMiniprogram.TouchEvent) => void
  goPlayList: (e: WechatMiniprogram.TouchEvent) => void
  getSong: (e: WechatMiniprogram.CustomEvent) => void
  handleLogout: () => void
  start: number //用于触发顶部下拉效果时记录初始触摸位置
  pageScrollTop: number //用于记录整个页面当前滚动条距离顶部的数值
}
type Instance = WechatMiniprogram.Page.Instance<DataModel, CustomOptionModel>
